<!--
 * @Author: LiYuan
 * @Date: 2021-04-08 11:17:04
 * @LastEditTime: 2022-11-23 10:53:22
 * @LastEditors: huangbc
 * @Description: 
 * You build it, You run it.
-->
<template>
  <div class="card-info">
    
    <!-- start 连接器类型的附加组件 -->
    <template v-if="isConnectorCard(cardInfo)">
      
      <connector-card-warper
        :main-module-value="workEvent"
        :card="cardInfo"
        :card-info="cardInfo"
        :event="workEvent"
        :bizId="eventId"
        :share-data="shareData"
        visible
      />
      
    </template>
    <!-- end 连接器类型的附加组件 -->
    
    <!-- start 其他类型附加组件 -->
    <template v-else>
      
      <!-- 多选 -->
      <template v-if="cardInfo.inputType === 'multiple'" >
        <multiple-card
          :event="workEvent"
          :card-info="cardInfo"
          :value="getCardValue(cardInfo.cardId)"
          @deleteCard="deleteCard"
          @editCard="editCard"
        >
        </multiple-card>
      </template>
      
      <!-- 单选 -->
      <template v-if="cardInfo.inputType === 'single'">
        <single-card
          :event="workEvent"
          :card-info="cardInfo"
          :value="getCardValue(cardInfo.cardId)"
          v-bind="$attrs"
          @deleteCard="deleteCard"
          @editCard="editCard"
        >
        </single-card>
      </template>
      
    </template>
    <!-- end 其他类型附加组件 -->
    
    <!-- 编辑弹窗 -->
    <base-modal :title="editTitle" :show.sync="editVisible" width="600px" @close="close">
      <form-builder ref="formEditRef" mode="event_card" :fields="fields" :value="value" @update="update" v-if="init" formEditingMode="edit" @getDeleteFiles="getDeleteFiles"></form-builder>
      <div slot="footer">
        <el-button @click="close">{{$t('common.base.close')}}</el-button>
        <el-button type="primary" @click="handleSave" :disabled="loading">{{$t('common.base.save')}}</el-button>
      </div>
    </base-modal>
  </div>
</template>

<script>
import * as EventApi from '@src/api/EventApi.js';
/* util */
import * as Utils from '@src/component/form/util';

import MultipleCard from './MultipleCard'
import SingleCard from './SingleCard'
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormSubmitTime } = useFormTimezone()
/* service */
import { isConnectorCard } from '@service/CardService';
/* components */
import ConnectorCardWarper from './ConnectorCard.vue'

export default {
  name: 'card-info',
  components: {
    MultipleCard,
    SingleCard,
    ConnectorCardWarper
  },
  props: {
    workEvent: {
      type: Object,
      default: () => {}
    },
    cardInfo: {
      type: Object,
      default: ()=> {}
    }
  },
  computed: {
    fields() {
      return Utils.migration(this.cardInfo.fields || []);
    },
    eventId() {
      return this.workEvent?.id || ''
    }
  },
  data() {
    return { 
      editTitle: this.$t('task.detail.components.addComponentInfo'),
      editVisible: false,
      loading: false,
      init: false,
      value: {},
      shareData: {},
      needServerDeleFiles:[]
    }
  },
  methods: {
    isConnectorCard,
    /** 
    * @description 获取指定附加组件数据
    */
    getCardValue(cardId) {
      let { cardInfo = [] } = this.workEvent;
      return cardInfo.filter(card => card.cardId == cardId)[0];
    },

    // 更新表单
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;
      let value = this.value;
      this.$set(value, fieldName, newValue);
      this.$emit('input', value);
    },

    // 弹窗关闭重置数据
    close() {
      this.editVisible = false;
      this.value = {};
      this.init = false;
      this.needServerDeleFiles = [];
    },

    // 打开新建编辑弹窗
    editCard(value) {
      this.editVisible = true

      this.$nextTick(()=> {
        let { attribute = {} } = value;
        this.value = Utils.initialize(this.cardInfo.fields, { attribute });
        this.editTitle = attribute.id ? this.$t('task.detail.components.editComponentInfo') : this.$t('task.detail.components.addComponentInfo');
        this.init = true;
      })
    },

    // 构建参数
    buildParams() {
      // 处理国际化时间转换
      let formValue = disposeFormSubmitTime(this.fields, this.value)
      const { attribute } = formValue
      const { cardId, inputType } = this.cardInfo;
      let card = {
        attribute: {
          id: attribute.id || ''
        },
        cardId,
        inputType
      }
      
      this.cardInfo.fields.forEach(field => {
        card.attribute[field.fieldName] = formValue[field.fieldName];
      })
      
      card = this.globalFormSubmissionDataProcessingHandler(this.cardInfo.fields, card)

       if(this.needServerDeleFiles.length){
        card.deleteFiles = this.needServerDeleFiles
      }
      
      return {
        eventId: this.workEvent.id,
        cardJson: JSON.stringify(card)
      }
    },

    // 编辑新建弹窗保存
    handleSave() {
      this.$refs.formEditRef
        .validate(false)
        .then(async valid => {
          if (!valid) return Promise.reject('validate fail.');

          const params = this.buildParams();

          // 编辑
          if(this.value?.attribute?.id) {
            this.editCardInfo(params);
          } else {
            this.saveCardInfo(params);
          }
        })
        .catch(err => {
          console.error(err);
        });
    },

    // 编辑
    editCardInfo(params) {
      this.loading = true;

      EventApi.eventEditCardInfo(params)
        .then(res => {
          this.$notify({
            title: res.status === 0 ? this.$t('common.base.success') : this.$t('common.base.error'),
            message: res.status === 0 ? this.$t('common.base.saveSuccess') : res.message,
            type: res.status === 0 ? 'success' : 'error'
          });
          if(res.status === 0){
            this.updateData()
          }
          // setTimeout(() => {
          //   window.location.href = `/event/view/${this.workEvent.id}`;
          // }, 1000)
        })
        .finally(()=> {this.loading = false})
    },

    // 保存
    saveCardInfo(params) {
      this.loading = true;
      EventApi.eventSaveCardInfo(params)
        .then(res => {
          this.$notify({
            title: res.status === 0 ? this.$t('common.base.success') : this.$t('common.base.error'),
            message: res.status === 0 ? this.$t('common.base.saveSuccess') : res.message,
            type: res.status === 0 ? 'success' : 'error'
          });
          if(res.status === 0){
            this.updateData()
          }
          // setTimeout(() => {
          //   window.location.href = `/event/view/${this.workEvent.id}`;
          // }, 1000)
        })
        .finally(()=> {this.loading = false})
    },

    // 删除
    deleteCard(infoId) {
      this.$confirm(this.$t('event.detail.components.cardInfo.text1'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(() => {
          const params = {
            cardId: this.cardInfo.cardId,
            infoId,
            eventId: this.workEvent.id
          }
          EventApi.eventDeleteCardInfo(params).then((res) => {
            this.$notify({
              title: res.status == 0 ? this.$t('common.base.success') : this.$t('common.base.error'),
              message: res.status == 0 ? this.$t('common.base.deleteSuccess') : res.message,
              type: res.status == 0 ? 'success' : 'error'
            });
            if(res.status === 0){
              this.updateData()
            }
            // setTimeout(() => {
            //   window.location.href = `/event/view/${this.workEvent.id}`;
            // }, 1000)
          });
        })
        .catch(() => { });
    },
    // 更新卡片
    updateData(){
      this.editVisible = false;
      this.needServerDeleFiles = [];
      setTimeout(()=>{
        this.$emit('updateCard')
      }, 200)
    },
    getDeleteFiles(files){
      this.needServerDeleFiles = [...this.needServerDeleFiles,...files]
    }
  }
}
</script>

<style lang="scss" scoped>

</style>